package org.jeecg.modules.demo.hd.controller;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.HttpServletRequestUtil;
import org.jeecg.common.vo.RequestVo;
import org.jeecg.modules.demo.hd.entity.AppUserGoldDetail;
import org.jeecg.modules.demo.hd.service.IAppUserGoldDetailService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.hd.vo.UserDayGoldTotalVo;
import org.jeecg.modules.demo.hd.vo.UserDayGoldTypeTotalViewVo;
import org.jeecg.modules.demo.hd.vo.UserDayGoldTypeTotalVo;
import org.jeecg.modules.demo.hd.vo.total.ChildUserGoldInputVo;
import org.jeecg.modules.demo.hd.vo.total.ChildUserGoldViewVo;
import org.jeecg.modules.demo.hd.vo.total.UserGoldDetailViewVo;
import org.jeecg.modules.system.entity.AppUserDeviceLog;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.IAppUserDeviceLogService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 用户金币获取明细记录
 * @Author: jeecg-boot
 * @Date: 2025-02-04
 * @Version: V1.0
 */
@Api(tags = "用户金币")
@RestController
@RequestMapping("/hd/appUserGoldDetail")
@Slf4j
public class AppUserGoldDetailController extends JeecgController<AppUserGoldDetail, IAppUserGoldDetailService> {
    @Autowired
    private IAppUserGoldDetailService appUserGoldDetail2Service;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IAppUserDeviceLogService deviceLogService;

    /**
     * 分页列表查询
     *
     * @param appUserGoldDetail2
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "用户金币获取详情列表查询-后台使用", notes = "用户金币获取详情列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<AppUserGoldDetail>> queryPageList(AppUserGoldDetail appUserGoldDetail2,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<AppUserGoldDetail> queryWrapper = QueryGenerator.initQueryWrapper(appUserGoldDetail2, req.getParameterMap());
        Page<AppUserGoldDetail> page = new Page<AppUserGoldDetail>(pageNo, pageSize);
        IPage<AppUserGoldDetail> pageList = appUserGoldDetail2Service.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @ApiOperation(value = "用户金币获取详情列表查询-APP用户查询", notes = "用户金币获取详情列表查询")
    @GetMapping(value = "/currentList")
    public Result<IPage<UserGoldDetailViewVo>> queryCurrentPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                    HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算7天前的日期
        LocalDateTime sevenDaysAgo = now.minusDays(7);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String day = sevenDaysAgo.format(formatter);
        Page<AppUserGoldDetail> page = new Page<AppUserGoldDetail>(pageNo, pageSize);
        IPage<UserGoldDetailViewVo> userGoldList = appUserGoldDetail2Service.getUserGoldList("", sysUser.getId(), day, page);
        return Result.OK(userGoldList);
    }

    @ApiOperation(value = "每日用户获得金币统计", notes = "每日用户获得金币统计")
    @GetMapping(value = "/UserDayGoldTotal")
    public Result<List<UserDayGoldTotalVo>> UserDayGoldTotal(@RequestParam(name = "day", required = true) String day) {
        List<UserDayGoldTotalVo> list = this.appUserGoldDetail2Service.getUserDayGoldTotalList(day);
        return Result.OK(list);
    }


    @ApiOperation(value = "获取当天按照用户和金币分类统计", notes = "获取当天按照用户和金币分类统计")
    @GetMapping(value = "/getUserDayGoldTypeTotalList")
    public Result<List<UserDayGoldTypeTotalViewVo>> getUserDayGoldTypeTotalList() {
        List<UserDayGoldTypeTotalVo> userDayGoldTypeTotalList = this.appUserGoldDetail2Service.getUserDayGoldTypeTotalList();
        List<String> userList = userDayGoldTypeTotalList.stream().map(item -> item.getUserId()).distinct().collect(Collectors.toList());
        List<UserDayGoldTypeTotalViewVo> data = new ArrayList<>();
        userList.forEach(item -> {
            UserDayGoldTypeTotalViewVo vo = new UserDayGoldTypeTotalViewVo();
            Optional<UserDayGoldTypeTotalVo> first = userDayGoldTypeTotalList.stream().filter(i -> i.getUserId().equals(item) && i.getGoldType().equals("0")).findFirst();
            if (first.isPresent()) {
                vo.setGoldNum(first.get().getGoldNum());
                vo.setUserName(first.get().getUserName());
                vo.setClickNum(first.get().getClickNum());
            }
            Optional<UserDayGoldTypeTotalVo> first2 = userDayGoldTypeTotalList.stream().filter(i -> i.getUserId().equals(item) && i.getGoldType().equals("2")).findFirst();
            if (first2.isPresent()) {
                vo.setPtjlGoldNum(first2.get().getGoldNum());
                vo.setUserName(first2.get().getUserName());
            }
            vo.setTotalNum(vo.getGoldNum() + vo.getPtjlGoldNum());
            vo.setUserId(item);
            data.add(vo);
        });
        return Result.OK(data);
    }

    //
    @ApiOperation(value = "查看团队下人员当日收益和点击次数", notes = "查看团队下人员当日收益和点击次数")
    @GetMapping(value = "/queryChildUserGoldList")
    public Result<IPage<ChildUserGoldViewVo>> queryChildUserGoldList(ChildUserGoldInputVo vo,
                                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                     HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser user = userService.getById(sysUser.getId());
        String date = DateUtils.getDate("yyyy-MM-dd");
        if (StringUtils.isNotEmpty(vo.getDay())) {
            date = vo.getDay();
        }
        IPage<ChildUserGoldViewVo> data = appUserGoldDetail2Service.getChildUserGoldNumTotalList(user.getGenCode(), date, new Page(pageNo, pageSize));
        return Result.OK(data);
    }

    @ApiOperation(value = "查看团队下人员当日收益和点击次数(汇总)", notes = "查看团队下人员当日收益和点击次数（汇总）")
    @GetMapping(value = "/queryChildUserGoldTotal")
    public Result<ChildUserGoldViewVo> queryChildUserGoldTotal(ChildUserGoldInputVo vo) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser user = userService.getById(sysUser.getId());
        String date = DateUtils.getDate("yyyy-MM-dd");
        if (StringUtils.isNotEmpty(vo.getDay())) {
            date = vo.getDay();
        }
        String genCode = user.getGenCode();
        if (user.getGenCode().equals("666666") || user.getGenCode().equals("888888")) {
            genCode = "";
        }
        ChildUserGoldViewVo data = appUserGoldDetail2Service.getChildUserGoldNumTotal(genCode, date);
        return Result.OK(data);
    }


    @ApiOperation(value = "获取用户金币获得明细", notes = "获取用户金币获得明细")
    @GetMapping(value = "/queryChildUserGoldByUserId")
    public Result<IPage<UserGoldDetailViewVo>> queryChildUserGoldByUserId(ChildUserGoldInputVo vo,
                                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                          HttpServletRequest req) {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 保存设备请求日志
        RequestVo requestVo = HttpServletRequestUtil.getDeviceInfoVo(req);
        AppUserDeviceLog deviceInfoVo = new AppUserDeviceLog();
        BeanUtils.copyProperties(requestVo, deviceInfoVo);
        deviceInfoVo.setUserId(currentUser.getId());
        deviceInfoVo.setRequestUrl("查询用户账户余额");
        deviceLogService.save(deviceInfoVo);
        IPage<UserGoldDetailViewVo> data = appUserGoldDetail2Service.getUserGoldDetailList(vo, new Page(pageNo, pageSize));
        return Result.OK(data);
    }


    @ApiOperation(value = "查看用户金币统计数据", notes = "查看用户金币统计数据")
    @GetMapping(value = "/getUserGoldTotalList")
    public Result<IPage<ChildUserGoldViewVo>> getUserGoldTotalList(ChildUserGoldInputVo vo,
                                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                   HttpServletRequest req) {
        String date = DateUtils.getDate("yyyy-MM-dd");
        if (StringUtils.isEmpty(vo.getDay())) {
            vo.setDay(date);
        }
        IPage<ChildUserGoldViewVo> data = appUserGoldDetail2Service.getUserGoldTotalList(vo, new Page(pageNo, pageSize));
        return Result.OK(data);
    }

}
